<template>
  <Card :bordered="false">
    <p slot="title">
      <Icon type="md-navigate"></Icon>
      镜像推送
    </p>
    <div style="padding-bottom: 10px;">
      <Row>
        <Col span="6">
          <Cascader :data="selec_env_men"  @on-change=data_list trigger="hover"></Cascader>
        </Col>
        <Col span="6" offset="12">
          <Input search placeholder="Search ..." v-model="searchValue" @on-search=searchImage />
        </Col>
      </Row>
    </div>
    <div>
      <Table ref="selection" :border=false :columns="columns" :data="data" @on-select="selectChange" @on-select-cancel="selectCancel" @on-select-all-cancel="selectCancel" @on-select-all="selectAll">
        <template slot-scope="{ row, index }" slot="index">
          <span>{{index+1}}</span>
        </template>
        <template slot-scope="{ row, index }" slot="action">
          <Button type="info" size="small" style="margin-right: 5px" @click="imageView(index)">查看</Button>
          <Button v-if="permission.push_oprate ==='1'" type="warning" size="small" style="margin-right: 5px" @click="selectPushView(index)">推送</Button>
        </template>
      </Table>
      <Modal v-model="PushtModal" :footer-hide="true" mask :mask-closable="false" title="镜像推送">
        <div style="padding-bottom: 10px;">
          <Table stripe :columns="selectPushcolumns" :data="paginationPushData">
            <template slot-scope="{ row, index }" slot="index">
              <span>{{index+1}}</span>
            </template>
            <template slot-scope="{ row, index }" slot="status">
              <span style="color:#19be6b; font-weight:bold"  v-if="`${ row.status }` == 'true'">推送成功</span>
              <span style="color:#ed4014; font-weight:bold" v-if="`${ row.status }` == 'false'">推送失败</span>
              <span style="color:#2d8cf0; font-weight:bold" v-if="`${ row.status }` == 'waiting'">待推送</span>
              <span style="color:#ff9900; font-weight:bold" v-if="`${ row.status }` == 'pushing'">正在推送</span>
            </template>
          </Table>
          <div style="padding-top: 10px;">
            <!-- 当推送的数据大于5条时分页 -->
            <template v-if="selectPushDataCount >= 5">
              <Page :total="selectPushDataCount" :page-size="5" current.sync="current" size="small" show-total @on-change="PushSwitchPage" />
            </template>
          </div>
        </div>
        <Row>
          <Col span="10">
            <Select v-if="!push_loading" v-model="remoteRepoEnv" :clearable="true" ref="store">
              <Option v-for="item in envList" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
            <Select v-else disabled v-model="remoteRepoEnv" :clearable="true" ref="store">
              <Option v-for="item in envList" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
          </Col>
          <Col span="8" offset="6">
            <Button type="success" style="margin-right: 5px" @click="pushing" :loading="push_loading">
              <span v-if="!push_loading">确认推送</span>
              <span v-else>推送中...</span>
            </Button>
            <Button type="warning" @click="closePushView">关闭</Button>
          </Col>
        </Row>
        <!-- 自定义页眉按键 -->
        <div slot="close">
          <!-- <a href="#" slot="extra" @click.prevent="closePushView">
            <Icon size="18" type="md-close"> </Icon>
          </a> -->
        </div>
      </Modal>
      <div style="padding-top: 10px;" v-if="count">
        <Row >
        <!-- <Col span="18"> -->
        <Col :xxl="16" :xl="12" :lg="8">
          <template v-if="permission.push_oprate ==='1'">
            <Button type="info" style="margin-right: 5px" @click="handleSelectAll(true)">全选</Button>
            <Button type="info" style="margin-right: 5px" @click="handleSelectAll(false)">取消</Button>
            <Button type="info" style="margin-right: 5px" @click="selectAllPushView">推送</Button>
          </template>
        </Col>
        <!-- <Col span="6"> -->
        <Col :xxl="8" :xl="12" :lg="16">
          <template>
            <Page :total="count" show-total :page-size-opts="[10,25,40,55,70,100]" current.sync="current" show-elevator show-sizer @on-change="switchPage" @on-page-size-change="switchPageSize" />
          </template>
        </Col>
      </Row>
      </div>
    </div>
  </Card>
</template>

<script>
import { imageList, imageSearch, imagePush } from '@/api/images'
import { deployConfTypeDetail, deployConfEnvsDetail } from '@/api/deploy'

  export default {
    data () {
      return {
        search_value: '',
        searchValue: '',
        count: null,
        env: '',
        appType: '',
        page: 1,  //设置默认页码为1
        pageSize: 10, //设置每页总条数默认为10条
        selec_env_men: [],
        data: [],
        selectPushData: [],
        paginationPushData: [],
        selectPushDataCount: null,
        selectPushDataPage: 1,
        PushtModal: false,
        push_loading: false,
        remoteRepoEnv: '',
        image_id_list: [],
        env_names: [],
        language_types: [],
        columns: [
          {
            type: 'selection',
            width: 60,
            align: 'center'
          },
          {
            title: '序号',
            slot: 'index',
            width:100
          },
          {
            title: '名称',
            key: 'name'
          },
          {
            title: '项目类型',
            key: 'application_type'
          },
          {
            title: '标签',
            key: 'tag'
          },
          {
            title: '创建日期',
            key: 'create_time'
          },
          {
            title: '更新日期',
            key: 'update_time'
          },
          {
            title: '操作',
            slot: 'action',
            // width: 200,
            align: 'center'
          }
        ],
        selectPushcolumns : [
          {
            title: '序号',
            slot: 'index',
            width: 60
          },
          {
            title: '名称',
            key: 'name'
          },
          // {
          //   title: '项目类型',
          //   key: 'application_type'
          // },
          {
            title: '标签',
            key: 'tag'
          },
          {
            title: '状态',
            key: 'status',
            slot: 'status'
          },
        ],
        envList : [],
        permission: '',
      }
    },
    mounted () {
      this.mens()
    },
    created () {
      this.get_permission()
    },
    methods: {
      // 获取用户操作权限
      get_permission () {
        const auth = JSON.parse(sessionStorage.getItem('permission'))
        this.permission = auth.child
      },
      // 应用发布菜单
      mens () {
        var envs = []
        this.env_names.push({'value':'prod','label':'生产环境'})
        // 获取所有开发语言类
        deployConfEnvsDetail().then(res => {
          var envs_data = res.data.results
          for (var service_type in envs_data) {
            if (envs_data[service_type].name != 'dev' && envs_data[service_type].name != 'test') {
              this.envList.push({'value':envs_data[service_type].name,'label':envs_data[service_type].label})
            }
          }
        })
        deployConfTypeDetail().then(res => {
          var types_data = res.data.results
          for (var language_type in types_data) {
            this.language_types.push({'value':types_data[language_type].name,'label':types_data[language_type].name})
          }
          // 生产select格式数据
          for (var env in this.env_names) {
            var params = {
              value: this.env_names[env].value,
              label: this.env_names[env].label,
              children: this.language_types
            }
            this.selec_env_men.push(params)
          }
        })
      },
      // 获取全部镜像数据
      data_list (data) {
        var env = data[0]
        var appType = data[1]
        this.env = env
        this.appType = appType
        imageList(appType, 1, 10, this.searchValue).then(res => {
          this.data = res.data.results
          this.count = res.data.count
        })
      },
      // 查看镜像信息
      imageView (index) {
        this.$Modal.info({
          title: '详细信息',
          width: 30,
          content: `项目名称：${this.data[index].name}<br>项目类型：${this.data[index].application_type}<br>镜像标签：${this.data[index].tag}<br>生成日期：${this.data[index].create_time}<br>更新日期：${this.data[index].update_time}<br>test仓库：${this.data[index].test}`
        })
      },
      // 获取页码并发起请求
      switchPage (page) {
        this.page = page
        imageList(this.appType, this.page, this.pageSize, this.searchValue).then(res => {
          this.data = res.data.results
        }).catch(err => {
          this.$Message.error('接口请求失败')
        })
      },
      // 获取选择切换的每页条数并发起请求
      switchPageSize (pageSize) {
        this.page = 1
        this.pageSize = pageSize
        imageList(this.appType, this.page, this.pageSize, this.searchValue).then(res => {
          this.data = res.data.results
        }).catch(err => {
          this.$Message.error('接口请求失败')
        })
      },
      // 搜索,支持模糊查询
      searchImage () {
        if (this.env.length!=0) {
          imageSearch(this.appType, this.searchValue).then(res => {
            this.data = res.data.results
            this.count = res.data.count
          }).catch(err => {
            this.$Message.error('接口请求失败!')
          })
        } else {
          this.$Message.error("请选择环境!")
        }
      },
      // 全选和取消 触发事件
      handleSelectAll (status) {
        this.$refs.selection.selectAll(status);
      },
      // 推送单个镜像时弹出推送窗口
      selectPushView (index) {
        this.PushtModal = true;
        this.image_id_list = [];
        this.image_id_list.push(this.data[index].id);
        this.selectPushData.push(this.data[index]);
        // this.paginationPushData.push(this.data[index]);
        this.pagination(1,this.selectPushData)
        this.selectPushDataCount = this.paginationPushData.length
        this.data[index]['status'] = 'waiting'
      },
      // 选择多个镜像推送时弹出窗口
      selectAllPushView () {
        if (this.selectPushData.length != 0) {
          this.PushtModal = true;
          this.selectPushDataCount = this.selectPushData.length;  // 统计推送数据的数量 以方便进行分页
        } else {
          this.$Message.info("请选择要推送的镜像!")
        }
      },
      // 执行推送
      pushing () {
        if (this.remoteRepoEnv.length !=0) {
          this.push_loading = true;
          var newSelectPushData = []
          for (const key in this.selectPushData) {
            var newPushStatusData = {}
            newPushStatusData['name'] = this.selectPushData[key].name
            newPushStatusData['tag'] = this.selectPushData[key].tag
            newPushStatusData['status'] = "pushing"
            newSelectPushData.push(newPushStatusData);
          }
          this.selectPushData = newSelectPushData;
          this.pagination(1,this.selectPushData)  //分页显示
          imagePush(this.remoteRepoEnv,this.image_id_list).then(res => {
            this.selectPushData =  res.data;
            this.pagination(1,this.selectPushData)  //分页显示
            this.push_loading = false;
            this.$Message.info({content:'操作完成!',duration: 5,closable: true})
          }).catch(err => {
            this.push_loading = false;
            var newSelectPushData_false = []
            for (const key in this.selectPushData) {
              var newPushStatusData_false = {}
              newPushStatusData_false['name'] = this.selectPushData[key].name
              newPushStatusData_false['tag'] = this.selectPushData[key].tag
              newPushStatusData_false['status'] = "false"
              newSelectPushData_false.push(newPushStatusData_false);
            }
            this.selectPushData = newSelectPushData_false;
            this.pagination(1,this.selectPushData)  //分页显示
            this.$Message.error({content:'接口请求失败!',duration: 15,closable: true})
          })
        } else {
          this.$Message.warning("请选择要推送的远程仓库！")
        }
      },
      // 推送窗口关闭事件 重置相关状态
      closePushView () {
        if (this.push_loading === true) {
          this.$Message.warning("请等待推送结果!")
        } else {
        // this.$refs.store.clearSingleSelect();  //清空select选择器
        this.PushtModal = false
        this.paginationPushData = []  //清空推送数据
        this.$refs.selection.selectAll(false);  //清空多选项
        }
      },
      //更改数据内容
      updateSelectData (data) {
        var newSelectPushData = [];
        this.image_id_list = [];  // 清空镜像id
        for (const key in data) {
          var newPushStatusData = {}
          newPushStatusData['name'] = data[key].name
          newPushStatusData['tag'] = data[key].tag
          newPushStatusData['status'] = "waiting"
          this.image_id_list.push(data[key].id) //存储镜像id
          newSelectPushData.push(newPushStatusData);  //替换需要推送的镜像数据
        }
        this.selectPushData = newSelectPushData;
        this.pagination(1,this.selectPushData)
        this.selectPushDataCount = this.selectPushData.length;  // 统计推送数据的数量 以方便进行分页
      },
      // 全选触发的事件
      selectAll (selection) {
        this.updateSelectData(selection)
      },
      // 点击多选框时触发
      selectChange (selection) {
        this.updateSelectData(selection)
      },
      // 取消多选框时触发
      selectCancel (selection) {
        this.updateSelectData(selection)
      },
      //推送窗口分页
      PushSwitchPage (page) {
        this.pagination(page,this.selectPushData)
      },
      // 对选择推送的数据进行分页
      pagination (page,data) {
        var default_page = 1; //默认页
        var default_PageSize = 5; //条数
        var PageSize = default_PageSize * page  //索引结尾
        var index = (page - default_page) * default_PageSize  //索引开头
        this.paginationPushData = data.slice(index,PageSize)  //数据切片
      }
    },
    mounted () {
      this.mens()
    }
  }
</script>
